package com.cwz.auth.controller;

import com.cwz.api.model.LoginUser;
import com.cwz.auth.model.LoginBody;
import com.cwz.auth.model.RegisterBody;
import com.cwz.auth.service.SysLoginService;
import com.cwz.core.result.R;
import com.cwz.core.utils.jwt.JwtHS512Utils;
import com.cwz.core.utils.string.StringUtils;
import com.cwz.security.auth.AuthUtil;
import com.cwz.security.service.TokenService;
import com.cwz.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @program: w-demo
 * @description: token 控制器
 * @author: Wen
 **/
@RestController
public class TokenController {
	@Autowired
	private TokenService tokenService;
	@Autowired
	private SysLoginService sysLoginService;

	/**
	 * @Description: 登录
	 * @Author: Wen
	 * @param loginBody: 输入信息
	 * @return: com.cwz.core.result.R<java.util.Map<java.lang.String,java.lang.Object>>
	 **/
	@PostMapping("/login")
	public R<Map<String, Object>> login(@RequestBody LoginBody loginBody) {
		// 用户登录
		LoginUser userInfo = this.sysLoginService.login(loginBody.getUsername(), loginBody.getPassword());
		// 获取登录token
		return R.ok(tokenService.createToken(userInfo));
	}

	/**
	 * @Description: 登出
	 * @Author: Wen
	 * @param request:
	 * @return: com.cwz.core.result.R<java.lang.Void>
	 **/
	@DeleteMapping("/logout")
	public R<Void> logout(HttpServletRequest request) {
		String token = SecurityUtils.getToken(request);
		if (StringUtils.isNotEmpty(token)) {
			String userName = JwtHS512Utils.getUserName(token);
			// 删除用户缓存记录
			AuthUtil.logoutByToken(token);
			// 记录用户退出日志
			this.sysLoginService.logout(userName);
		}
		return R.ok();
	}

	/**
	 * @Description: 刷新 token
	 * @Author: Wen
	 * @param request:
	 * @return: com.cwz.core.result.R<java.lang.Void>
	 **/
	@PostMapping("/refresh")
	public R<Void> refresh(HttpServletRequest request) {
		LoginUser loginUser = this.tokenService.getLoginUser(request);
		if (StringUtils.isNotNull(loginUser)) {
			// 刷新令牌有效期
			this.tokenService.refreshToken(loginUser);
		}
		return R.ok();
	}

	/**
	 * @Description: 注册
	 * @Author: Wen
	 * @param registerBody:	输入信息
	 * @return: com.cwz.core.result.R<java.lang.Void>
	 **/
	@PostMapping("/register")
	public R<Void> register(@RequestBody RegisterBody registerBody) {
		// 用户注册
		this.sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
		return R.ok();
	}
}
